<template>
  <div>
    <el-upload
      class="upload-demo"
      :auto-upload="false"
      :on-change="handleChange"
      :on-submit="handleSubmit"
      :http-request="uploadFile"
      :file-list="fileList"
      :limit="1"
      :on-exceed="handleExceed"
      ref="upload"
    >
      <template #trigger>
        <el-button slot="trigger" type="primary">选取文件</el-button>
      </template>
      <el-button type="success" @click="submitUpload">上传到服务器</el-button>
      <template #tip>
        <div class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </template>
    </el-upload>
  </div>
</template>

<script>
import { ref,onMounted } from 'vue';
import { UploadApi } from '@/apis/uploadApi.js';
import {favoriteApi} from "@/apis/favoriteApi.js";
import {genFileId} from "element-plus";

export default {
  setup() {
    const upload = ref(null);
    const fileList = ref([]);

    const handleChange = (file, fileList) => {
      // 限制只能有一个文件
      if (fileList.length > 1) {
        fileList.shift();
      }
    };

    const handleSubmit = (file) => {
      console.log('Submitting file:', file);
    };

    const uploadFile = async (options) => {
      try {
        const res = await UploadApi.uploadImage(options.file);
        console.log('Upload successful:', res);
        // 可以在这里处理上传成功的逻辑，比如显示成功提示
      } catch (error) {
        console.error('Upload failed:', error);
        // 可以在这里处理上传失败的逻辑，比如显示错误提示
      }
    };

    const submitUpload = () => {
      upload.value.submit();
    };

    const handleExceed = (files) => {
      upload.value.clearFiles()
      const file = files[0];
      file.uid = genFileId()
      upload.value.handleStart(file)
    }
    onMounted(async()=>{
      const res = await favoriteApi.getFavoritesByCategory('默认收藏夹');
      console.log('收藏夹查询',res)
    })

    return {
      upload,
      fileList,
      handleChange,
      handleSubmit,
      uploadFile,
      submitUpload,
      handleExceed
    };
  }
};
</script>

<style scoped>
.upload-demo {
  margin-top: 20px;
}
</style>
